package com.yhn.controller;


import com.github.pagehelper.PageInfo;
import com.hospital.common.base.PageResult;
import com.hospital.common.base.Result;
import com.hospital.common.dto.section.*;
import com.hospital.common.pojo.TPostMeta;
import com.hospital.common.pojo.TSection;
import com.hospital.common.vo.section.module.SectionVo;
import com.yhn.service.SectionService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 板块服务控制器
 *
 * @author yhn
 * @version 1.0
 */
@RestController
@RequestMapping("/api/sections")
//@CrossOrigin(origins = "*", allowedHeaders = "*")
public class SectionController {
    @Resource
    private SectionService sectionService;

    /**
     * 创建板块
     *
     * @param req 创建请求参数
     * @param userId 当前登录用户ID（从请求头获取）
     * @return 创建后的板块信息
     */
    @PostMapping("/boards")
    public Result<TSection> createBoard(@Valid @RequestBody SectionCreateReqDto req,
                                        @RequestHeader("userId") Long userId) {
        TSection created = sectionService.createSection(userId, req);
        if (created == null) {
            return Result.fail(10001, "板块名称已存在");
        }
        if (created.getId() == null) {
            return Result.fail(40301, "无权限创建板块");
        }
        return Result.success(created);
    }

    /**
     * 编辑板块（REST）
     */
    @PutMapping("/boards/{id}")
    public Result<TSection> updateBoard(@PathVariable("id") Long id,
                                        @Valid @RequestBody SectionUpdateReqDto req,
                                        @RequestHeader("userId") Long userId) {
        req.setId(id);
        TSection updated = sectionService.updateSection(userId, req);
        if (updated == null) {
            return Result.fail(10001, "板块名称已存在");
        }
        if (updated.getId() == null) {
            return Result.fail(40301, "无权限编辑板块");
        }
        return Result.success(updated);
    }

    /**
     * 删除板块
     */
    @DeleteMapping("/boards/{id}")
    public Result<String> deleteBoard(@PathVariable("id") Long id,
                                      @RequestHeader("userId") Long userId) {
        Integer result = sectionService.deleteSection(userId, id);

        if (result == null) {
            return Result.fail(40401, "板块不存在");
        } else if (result == -1) {
            return Result.fail(40301, "无权限删除板块");
        } else if (result == 0) {
            return Result.fail(40901, "板块下有帖子，无法删除");
        } else {
            return Result.success("删除成功");
        }
    }

    /**
     * 分配版主
     */
    @PostMapping("/boards/assign-moderator")
    public Result<String> assignModerator(@Valid @RequestBody AssignModeratorReqDto req,
                                          @RequestHeader("userId") Long userId) {
        Integer result = sectionService.assignModerator(userId, req.getSectionId(), req.getDoctorUserId());

        if (result == null) {
            return Result.fail(40401, "板块不存在");
        } else if (result == -1) {
            return Result.fail(40301, "无权限分配版主");
        } else if (result == -2) {
            return Result.fail(40002, "该医生已经是其他板块的版主，一个医生只能管理一个板块");
        } else if (result == 0) {
            return Result.fail(40001, "医生不存在或角色不对");
        } else {
            return Result.success("分配版主成功");
        }
    }

    /**
     * 获取板块公告
     */
    @GetMapping("/boards/{id}/notice")
    public Result<TSection> getSectionNotice(@PathVariable("id") Long id) {
        TSection section = sectionService.getSectionNotice(id);
        if (section == null) {
            return Result.fail(40401, "板块不存在");
        }
        return Result.success(section);
    }

    /**
     * 更新板块公告
     */
    @PutMapping("/boards/notice")
    public Result<String> updateSectionNotice(@Valid @RequestBody SectionNoticeUpdateReqDto req,
                                              @RequestHeader("userId") Long userId) {
        Boolean result = sectionService.updateSectionNotice(userId, req.getSectionId(), req.getNotice());

        if (result == null) {
            return Result.fail(40401, "板块不存在");
        } else if (result == false) {
            return Result.fail(40301, "无权限操作此板块公告");
        } else {
            return Result.success("公告更新成功");
        }
    }

    /**
     * 帖子置顶操作
     */
    @PostMapping("/posts/{postId}/top")
    public Result<String> setPostTop(@PathVariable("postId") Long postId,
                                     @RequestParam(value = "isTop", defaultValue = "1") Integer isTop,
                                     @RequestHeader("userId") Long userId) {
        Boolean result = sectionService.setPostTop(userId, postId, isTop);

        if (result == null) {
            return Result.fail(40401, "帖子不存在");
        } else if (result == false) {
            return Result.fail(40301, "无权限操作此帖子");
        } else {
            String action = isTop == 1 ? "置顶" : "取消置顶";
            return Result.success("帖子" + action + "成功");
        }
    }

    /**
     * 帖子加精操作
     */
    @PostMapping("/posts/{postId}/pinned")
    public Result<String> setPostPinned(@PathVariable("postId") Long postId,
                                        @RequestParam(value = "isPinned", defaultValue = "1") Integer isPinned,
                                        @RequestHeader("userId") Long userId) {
        Boolean result = sectionService.setPostPinned(userId, postId, isPinned);

        if (result == null) {
            return Result.fail(40401, "帖子不存在");
        } else if (result == false) {
            return Result.fail(40301, "无权限操作此帖子");
        } else {
            String action = isPinned == 1 ? "加精" : "取消加精";
            return Result.success("帖子" + action + "成功");
        }
    }



    /**
     * 查询所有板块数量
     */
    @GetMapping("/count")
    public Result<Integer> getAllSectionsCount() {
        Integer count = sectionService.getAllSectionsCount();
        return Result.success(count);
    }

    /**
     * 查询所有板块
     */
    @GetMapping("/findAllSection")
    public Result<List<SectionVo>> findAllSection() {
        List<SectionVo> sectionVos = sectionService.findAllSection();
        return Result.success(sectionVos);
    }
    /**
     * 根据板块id查询板块
     */
    @GetMapping("/findSectionById")
    public Result<SectionVo> findSectionById(@RequestParam("id") Long id) {
        SectionVo sectionVo = sectionService.findSectionById(id);
        return Result.success(sectionVo);
    }
    /**
     * 根据版主id查询板块id
     * @param moderatorId 版主id
     */
    @GetMapping("/findSectionIdsByModeratorId")
    public Result<List<Long>> findSectionIdsByModeratorId(@RequestParam("moderatorId") Long moderatorId) {
        List<Long> sectionIds = sectionService.findSectionIdsByModeratorId(moderatorId);
        return Result.success(sectionIds);
    }
    /**
     * 分页查询所有板块
     * @param pageNum 页码
     * @param pageSize 每页数量
     */
    @GetMapping("/findAllSectionInPage")
    public Result<PageResult<SectionVo>> findAllSection(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize){
        PageResult<SectionVo> pageResult = sectionService.findAllSection(pageNum, pageSize);
        return Result.success(pageResult);
    }

    /**
     * 分页查询板块列表
     *
     * @param req 查询请求参数
     * @return 分页的板块列表
     */
    @GetMapping("/boards")
    public Result<PageInfo<SectionVo>> getSections(@Valid SectionQueryReqDto req) {
        PageInfo<SectionVo> pageInfo = sectionService.getSections(req);
        return Result.success(pageInfo);
    }

    /**
     * 分页查询帖子列表
     *
     * @param req 查询请求参数
     * @return 分页的帖子列表
     */
    @GetMapping("/posts")
    public Result<PageInfo<TPostMeta>> getPosts(@Valid PostQueryReqDto req) {
        PageInfo<TPostMeta> pageInfo = sectionService.getPosts(req);
        return Result.success(pageInfo);
    }

    /**
     * 获取所有医生列表（用于分配版主）
     *
     * @return 医生列表
     */
    @GetMapping("/doctors")
    public Result<List<Map<String, Object>>> getDoctors() {
        List<Map<String, Object>> doctors = sectionService.getDoctors();
        return Result.success(doctors);
    }
}
